package script

import (
	"autochat-script/script/api"
	"autochat-script/script/message"
	"github.com/samber/lo/mutable"
	"log"
	"math/rand"
	"sync"
	"time"
)

var clientList []*ChatClient
var spareUsers []string
var mutex sync.Mutex

func GetList() []*ChatClient {
	list := make([]*ChatClient, len(clientList))
	copy(list, clientList)
	return list
}

func GetClient(userId string) *ChatClient {
	for _, it := range clientList {
		// 如果需要根据ID来删除，可以使用下面的条件判断
		if it.UserId == userId {
			return it
		}
	}
	return nil
}

func RegisterClient(client *ChatClient) {
	mutex.Lock()
	defer mutex.Unlock()

	clientList = append(clientList, client)
	spareUsers = append(spareUsers, client.UserId)
}

func UnRegisterClient(client *ChatClient) {
	mutex.Lock()
	defer mutex.Unlock()

	for i, uid := range spareUsers {
		if uid == client.UserId { // 直接比较指针是否相同
			// 从切片中删除元素
			spareUsers = append(spareUsers[:i], spareUsers[i+1:]...)
			break
		}
	}

	for i, c := range clientList {
		if c == client { // 直接比较指针是否相同
			// 从切片中删除元素
			clientList = append(clientList[:i], clientList[i+1:]...)
			break
		}
	}
}

func RandomChat( /* client *ChatClient*/ ) {
	if len(spareUsers) < 2 {
		return
	}
	mutable.Shuffle(spareUsers)

	for {
		pair, flag := takeSpareLast(2)
		if flag {
			go func(userId string, sender string) {
				randIndex := rand.Intn(len(api.SpokenWords))
				text := api.SpokenWords[randIndex]
				GetClient(userId).Send(text, sender)
			}(pair[0], pair[1])
		} else {
			break
		}
	}
}

func ResponseChat(client *ChatClient, msg message.Message) {
	//随机停顿几秒
	time.Sleep(time.Duration(1+rand.Intn(5)) * time.Second)

	if client.Status == Status_Paused {
		return
	}

	userId := msg.Sender

	text := api.GetPreparedText(msg.Content)
	if text != "" {
		client.Send(text, userId)
	} else {
		log.Println("发送的text为空,已忽略")
	}
}

// Pause 暂停回复消息
func Pause(client *ChatClient) {
	if client.Status == Status_Active {
		client.Status = Status_Paused
		log.Println("暂停回复消息。 userId=", client.UserId)
	}
}

// Resume 恢复回复消息
func Resume(client *ChatClient) {
	if client.Status == Status_Paused {
		client.Status = Status_Active
		log.Println("恢复回复消息。 userId=", client.UserId)

		go func() {
			latestMsg := client.Messages[len(client.Messages)-1]
			ResponseChat(client, latestMsg)
		}()
	}
}

func takeSpareLast(size int) ([]string, bool) {
	mutex.Lock()
	defer mutex.Unlock()

	LEN := len(spareUsers)
	if LEN < size {
		return nil, false
	}
	// 取最后 size 个元素
	result := spareUsers[LEN-size:]
	// 更新原切片：保留前面的部分
	spareUsers = spareUsers[:LEN-size]
	return result, true
}

func matching(N int) [][]int {
	array := make([]bool, N) // 创建一个长度为N的数组，所有元素默认值为false

	selected := []int{}

	for len(selected) < N {
		index1 := rand.Intn(N)
		for array[index1] {
			index1 = (index1 + 1) % N
		}
		array[index1] = true
		selected = append(selected, index1)
	}

	// 输出配对
	var pairs [][]int
	for j := 1; j < len(selected); j += 2 {
		//fmt.Println("slice = ", selected[j-1], " _ ", selected[j])
		pair := []int{selected[j-1], selected[j]}
		pairs = append(pairs, pair)
	}
	return pairs
}
